package com.itheima.web.service.impl.pms;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.dto.pms.ProductCreateDto;
import com.itheima.result.PageResult;
import com.itheima.service.pms.PmsProductService;
import com.itheima.vo.pms.*;
import com.itheima.web.mapper.pms.PmsProductMapper;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@DubboService
public class PmsProductServiceImpl extends ServiceImpl<PmsProductMapper, Product> implements PmsProductService {
    @Autowired
    private PmsProductMapper pmsProductMapper;

    @Autowired
    private PmsProductServiceImpl pmsProductService;

    /**
     * 新增商品
     * @param productCreateDto
     * @return
     */
    @Override
    //涉及多张表，开启事物，要么同时成功，要么同时失败
    @Transactional
    public void addCreate(ProductCreateDto productCreateDto) {
        //拷贝出新增商品信息
        Product product = new Product();
        BeanUtils.copyProperties(productCreateDto , product);
        //添加商品
        int insert = pmsProductMapper.insert(product);
        Long productId = product.getId();
        //this.save(product);

        //保存商品的sku库存信息
        List<SkuStock> skuStockList = productCreateDto.getSkuStockList();
        if (skuStockList.size() != 0) {
            for (SkuStock skuStock : skuStockList) {
                skuStock.setProductId(productId);
                pmsProductMapper.addSkuStock(skuStock);
            }
        }

        //商品会员价格设置
        List<MemberPrice> memberPriceList = productCreateDto.getMemberPriceList();
        if (memberPriceList.size() != 0) {
            for (MemberPrice memberPrice : memberPriceList) {
                memberPrice.setProductId(productId);
                pmsProductMapper.addMemberPrice(memberPrice);
            }
        }

        //优选专区和商品的关系
        List<PrefrenceAreaProductRelation> prefrenceAreaProductRelationList = productCreateDto.getPrefrenceAreaProductRelationList();
        if (prefrenceAreaProductRelationList.size() != 0) {
            for (PrefrenceAreaProductRelation prefrenceAreaProductRelation : prefrenceAreaProductRelationList) {
                prefrenceAreaProductRelation.setProductId(productId);
                pmsProductMapper.addPrefrenceAreaProductRelation(prefrenceAreaProductRelation);
            }
        }

        //商品参数及自定义规格属性
        List<ProductAttributeValue> productAttributeValueList = productCreateDto.getProductAttributeValueList();
        if (productAttributeValueList.size() != 0) {
            for (ProductAttributeValue productAttributeValue : productAttributeValueList) {
                productAttributeValue.setProductId(productId);
                pmsProductMapper.addProductAttributeValue(productAttributeValue);
            }
        }

        //商品满减价格设置
        List<ProductFullReduction> productFullReductionList = productCreateDto.getProductFullReductionList();
        if (productFullReductionList.size() != 0) {
            for (ProductFullReduction productFullReduction : productFullReductionList) {
                productFullReduction.setProductId(productId);
                pmsProductMapper.addProductFullReduction(productFullReduction);
            }
        }

        //商品阶梯价格设置
        List<ProductLadder> productLadderList = productCreateDto.getProductLadderList();
        if (productLadderList.size() != 0) {
            for (ProductLadder productLadder : productLadderList) {
                productLadder.setProductId(productId);
                pmsProductMapper.addProductLadder(productLadder);
            }
        }

        //专题和商品关系
        List<SubjectProductRelation> subjectProductRelationList = productCreateDto.getSubjectProductRelationList();
        if (subjectProductRelationList.size() != 0) {
            for (SubjectProductRelation subjectProductRelation : subjectProductRelationList) {
                subjectProductRelation.setProductId(productId);
                pmsProductMapper.addSubjectProductRelation(subjectProductRelation);
            }
        }
    }

    /**
     * 查询商品
     * @param
     * @return
     */
    @Override
    public PageResult productList(Long brandId, String keyword, Long pageNum, Long pageSize, Long productCategoryId, String productSn, Integer publishStatus, Integer verifyStatus) {
        //创建分页构造器对象
        Page<Product> pageInfo = new Page<>(pageNum , pageSize);

        //添加查询条件
        LambdaQueryWrapper<Product> queryWrapper = new LambdaQueryWrapper<>();

        //条件构造器
        queryWrapper.eq(brandId != null , Product::getBrandId , brandId)
                .eq(productCategoryId != null , Product::getProductCategoryId , productCategoryId)
                .eq(productSn != null , Product::getProductSn , productSn)
                .eq(publishStatus != null , Product::getPublishStatus , publishStatus)
                .eq(verifyStatus != null , Product::getVerifyStatus , verifyStatus)
                .like(keyword != null , Product::getName , keyword)
                .orderByAsc(Product::getId);

        //执行查询
        this.page(pageInfo , queryWrapper);

        PageResult pageProduct = PageResult.init(pageInfo.getTotal(), pageSize, pageNum, pageInfo.getRecords());
        return pageProduct;

    }

    /**
     * 根据商品名称或货号模糊查询
     * @param keyword
     * @return
     */
    @Override
    public List<Product> keyword(String keyword) {
        //添加查询条件
        LambdaQueryWrapper<Product> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(Product::getName , keyword);
        return this.list(queryWrapper);
    }

    /**
     * 批量修改删除状态
     * @param deleteStatus
     * @param ids
     * @return
     */
    @Override
    public void updateDeleteStatus(Integer deleteStatus, List ids) {
        LambdaQueryWrapper<Product> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Product::getId , ids);
        List<Product> list = this.list(queryWrapper);
        List<Product> productList = list.stream().map(item -> {
            item.setDeleteStatus(deleteStatus);
            return item;
        }).collect(Collectors.toList());
        //this.updateBatchById(productList);
        this.removeByIds(productList);
    }

    /**
     * 批量设为新品
     * @param newStatus
     * @param ids
     * @return
     */
    @Override
    public void updateNewStatus(Integer newStatus, List<Integer> ids) {
        LambdaQueryWrapper<Product> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Product::getId , ids);
        List<Product> list = this.list(queryWrapper);
        List<Product> productList = list.stream().map(item -> {
            item.setNewStatus(newStatus);
            return item;
        }).collect(Collectors.toList());
        this.updateBatchById(productList);
    }

    /**
     * 批量上下架商品
     * @param publishStatus
     * @param ids
     * @return
     */
    @Override
    public void updatePublishStatus(Integer publishStatus, List<Integer> ids) {
        LambdaQueryWrapper<Product> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Product::getId , ids);
        List<Product> list = this.list(queryWrapper);
        List<Product> productList = list.stream().map(item -> {
            item.setPublishStatus(publishStatus);
            return item;
        }).collect(Collectors.toList());
        this.updateBatchById(productList);
    }

    /**
     * 批量推荐商品
     * @param recommendStatus
     * @param ids
     * @return
     */
    @Override
    public void updateRecommendStatus(Integer recommendStatus, List<Integer> ids) {
        LambdaQueryWrapper<Product> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Product::getId , ids);
        List<Product> list = this.list(queryWrapper);
        List<Product> productList = list.stream().map(item -> {
            item.setRecommandStatus(recommendStatus);
            return item;
        }).collect(Collectors.toList());
        this.updateBatchById(productList);
    }

    /**
     * 批量修改审核状态
     * @param verifyStatus
     * @param detail
     * @param ids
     * @return
     */
    @Override
    @Transactional
    public void updateVerifyStatus(Integer verifyStatus, String detail, List<Long> ids) {
        //添加审核记录
        String createTime = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date());
        String vertifyMan = "admin";
        int status = 1;
        for (Long id : ids) {
            pmsProductMapper.addVertifyRecord(id , createTime , vertifyMan , status , detail);
        }
        //批量推荐商品
        LambdaQueryWrapper<Product> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Product::getId , ids);
        List<Product> list = this.list(queryWrapper);
        List<Product> productList = list.stream().map(item -> {
            item.setVerifyStatus(verifyStatus);
            return item;
        }).collect(Collectors.toList());
        this.updateBatchById(productList);
    }

    /**
     * 根据商品id获取商品编辑信息
     * @param id
     * @return
     */
    @Override
    public ProductCreateDto updateInfo(Long id) {
        ProductCreateDto productCreateDto = new ProductCreateDto();
        //获取商品基本信息
        Product product = this.getById(id);
        BeanUtils.copyProperties(product , productCreateDto);
        //获取商品会员价格设置
        productCreateDto.setMemberPriceList(pmsProductMapper.getMemberPrice(id));
        //获取优选专区和商品的关系
        productCreateDto.setPrefrenceAreaProductRelationList(pmsProductMapper.getPrefrenceAreaProductRelation(id));
        //获取商品参数及自定义规格属性
        productCreateDto.setProductAttributeValueList(pmsProductMapper.getProductAttributeValue(id));
        //获取商品满减价格设置
        productCreateDto.setProductFullReductionList(pmsProductMapper.getProductFullReduction(id));
        //获取商品阶梯价格设置
        productCreateDto.setProductLadderList(pmsProductMapper.getProductLadderList(id));
        //获取商品的sku库存信息
        productCreateDto.setSkuStockList(pmsProductMapper.getSkuStockList(id));
        //获取专题和商品关系
        productCreateDto.setSubjectProductRelationList(pmsProductMapper.getSubjectProductRelationList(id));
        return productCreateDto;
    }

    /**
     * 更新商品
     * @param id
     * @param productCreateDto
     * @return
     */
    @Override
    @Transactional
    public void updateProduct(Long id, ProductCreateDto productCreateDto) {
        //更新商品信息
        Product product = new Product();
        BeanUtils.copyProperties(productCreateDto , product);
        product.setId(id);
        this.updateById(product);
        //修改或添加商品会员价格设置
        List<MemberPrice> memberPrice = pmsProductMapper.getMemberPrice(id);
        List<MemberPrice> memberPriceList = productCreateDto.getMemberPriceList();
        if (memberPrice.size() != 0) {
            if (memberPriceList.size() != 0) {
                for (MemberPrice memberPrice1 : memberPriceList) {
                    pmsProductMapper.updateMemberPrice(memberPrice1);
                }
            }
        }else {
            if (memberPriceList.size() != 0) {
                for (MemberPrice memberPrice2 : memberPriceList) {
                    pmsProductMapper.addMemberPrice(memberPrice2);
                }
            }
        }
        //修改或添加优选专区和商品的关系
        List<PrefrenceAreaProductRelation> list = productCreateDto.getPrefrenceAreaProductRelationList();
        List<PrefrenceAreaProductRelation> prefrenceAreaProductRelation = pmsProductMapper.getPrefrenceAreaProductRelation(id);
        if (prefrenceAreaProductRelation.size() != 0) {
            if (list.size() != 0) {
                for (PrefrenceAreaProductRelation areaProductRelation : list) {
                    pmsProductMapper.updatePrefrenceAreaProductRelation(areaProductRelation);
                }
            }
        }else {
            if (list.size() != 0) {
                for (PrefrenceAreaProductRelation areaProductRelation : list) {
                    pmsProductMapper.addPrefrenceAreaProductRelation(areaProductRelation);
                }
            }
        }
        //修改或添加商品参数及自定义规格属性
        List<ProductAttributeValue> productAttributeValueList = productCreateDto.getProductAttributeValueList();
        List<ProductAttributeValue> productAttributeValue = pmsProductMapper.getProductAttributeValue(id);
        if (productAttributeValue.size() != 0) {
            if (productAttributeValueList.size() != 0) {
                for (ProductAttributeValue attributeValue : productAttributeValueList) {
                    pmsProductMapper.updateProductAttributeValue(attributeValue);
                }
            }
        }else {
            if (productAttributeValueList.size() != 0) {
                for (ProductAttributeValue attributeValue : productAttributeValueList) {
                    pmsProductMapper.addProductAttributeValue(attributeValue);
                }
            }
        }

        //修改或添加商品满减价格设置
        List<ProductFullReduction> productFullReductionList = productCreateDto.getProductFullReductionList();
        List<ProductFullReduction> productFullReduction = pmsProductMapper.getProductFullReduction(id);
        if (productFullReduction.size() != 0) {
            if (productFullReductionList.size() != 0) {
                for (ProductFullReduction fullReduction : productFullReductionList) {
                    pmsProductMapper.updateProductFullReduction(fullReduction);
                }
            }
        }else {
            if (productFullReductionList.size() != 0) {
                for (ProductFullReduction fullReduction : productFullReductionList) {
                    pmsProductMapper.addProductFullReduction(fullReduction);
                }
            }
        }

        //修改或添加商品阶梯价格设置
        List<ProductLadder> productLadderList = productCreateDto.getProductLadderList();
        List<ProductLadder> productLadder = pmsProductMapper.getProductLadderList(id);
        if (productLadder.size() != 0) {
            if (productLadderList.size() != 0) {
                for (ProductLadder ladder : productLadderList) {
                    pmsProductMapper.updateProductLadder(ladder);
                }
            }
        }else {
            if (productLadderList.size() != 0) {
                for (ProductLadder ladder : productLadderList) {
                    pmsProductMapper.addProductLadder(ladder);
                }
            }
        }

        //修改或添加商品的sku库存信息
        List<SkuStock> skuStockList = productCreateDto.getSkuStockList();
        List<SkuStock> skuStocks = pmsProductMapper.getSkuStockList(id);
        if (skuStocks.size() != 0) {
            if (skuStockList.size() != 0) {
                for (SkuStock skuStock : skuStockList) {
                    pmsProductMapper.updateSkuStock(skuStock);
                }
            }
        }else {
            if (skuStockList.size() != 0) {
                for (SkuStock skuStock : skuStockList) {
                    pmsProductMapper.addSkuStock(skuStock);
                }
            }
        }

        //修改或添加专题和商品关系
        List<SubjectProductRelation> subjectProductRelationList = productCreateDto.getSubjectProductRelationList();
        List<SubjectProductRelation> productRelationList = pmsProductMapper.getSubjectProductRelationList(id);
        if (productRelationList.size() != 0) {
            if (subjectProductRelationList.size() != 0) {
                for (SubjectProductRelation subjectProductRelation : subjectProductRelationList) {
                    pmsProductMapper.updateSubjectProductRelation(subjectProductRelation);
                }
            }
        }else {
            if (subjectProductRelationList.size() != 0) {
                for (SubjectProductRelation subjectProductRelation : subjectProductRelationList) {
                    pmsProductMapper.addSubjectProductRelation(subjectProductRelation);
                }
            }
        }
    }


}
